<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { Patient } from '@/types/user'
import type { ConsultOrderData, PartialConsult } from '@/types/consult'
import { getPatientDetailById, getConsultOrderPre } from '@/services/consult'
import { useConsultStore } from '@/stores'
import {
  showToast,
  showConfirmDialog,
  showDialog,
  showLoadingToast
} from 'vant'
import { createConsultOrder, payConsultOrder } from '@/services/consult'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const router = useRouter()
const consultStore = useConsultStore()
const patientDetail = ref<Patient>()
const payInfo = ref<ConsultOrderData>()

// 获取病人详情
const initPatientDetail = async () => {
  let patientId = consultStore.consult.patientId
  const res = await getPatientDetailById(patientId as string)
  patientDetail.value = res.data
}

// 获取就诊信息
const initConsultOrder = async () => {
  const { type, illnessType } = consultStore.consult
  if (type && (illnessType === 0 || illnessType === 1)) {
    const { data } = await getConsultOrderPre({
      type,
      illnessType
    })
    payInfo.value = data
    // 设置优惠券
    consultStore.setCoupon(data.couponId)
  }
}
// 病人的简要信息
const briefPatientInfo = computed<string>(() => {
  // 李富贵 | 男 | 30岁
  if (!patientDetail.value) {
    return 'xx | xx | xx岁'
  } else {
    const { name, genderValue, age } = patientDetail.value
    return `${name} | ${genderValue} | ${age}岁`
  }
})

// Key 等价于 id | type | illnessType | depId | illnessDesc | illnessTime | consultFlag | patientId
type Key = keyof PartialConsult
onMounted(() => {
  // 先要判断store中的consult数据是否每一个都不是undefined。如果存在undefined，说明信息没填，没填就弹弹框
  const valideKeys: Key[] = [
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId'
  ]
  // 判断是否校验通过
  const isValide = valideKeys.every((key) => {
    // 原则是每一个都不等于undefined
    return consultStore.consult[key] !== undefined
  })
  // 如果没有通过，弹弹框
  if (!isValide) {
    showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
      closeOnPopstate: false
    }).then(() => {
      // 跳转到首页
      router.push('/')
    })
  }
  // 获取就诊信息
  initPatientDetail()
  initConsultOrder()
})

const isAgree = ref<boolean>(false)
const show = ref<boolean>(false)
const loading = ref<boolean>(false)
const paymentMethod = ref<0 | 1>()
const orderId = ref<string>('')
const onSubmit = async () => {
  if (!isAgree.value) {
    return showToast('请先同意支付协议')
  }
  // 发请求 去生成一个订单
  loading.value = true
  const { data } = await createConsultOrder(consultStore.consult)
  orderId.value = data.id
  // 生成订单以后需要清空store中的consult数据
  consultStore.clear()
  loading.value = false
  // 显示选择支付方式的弹框
  show.value = true
}
onBeforeRouteLeave((to, from) => {
  // 生成订单后就不能后退了
  if (orderId.value) return false
})

// 面板关闭的回调
const handleClose = () => {
  // 弹弹框
  showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付'
  })
    .then(() => {
      // 点击继续支付应该停留在当前页面
    })
    .catch(() => {
      // 点击取消支付跳转到另外一个页面,但是需要注意，如果orderId的值存在的话，是跳不了的，所以必须清空它
      orderId.value = ''
      router.push('/user/consult')
    })
}
const pay = async () => {
  if (!paymentMethod.value) return showToast('请选择支付方式')
  // 跳转支付loading加载
  // duration: 0 表示一直存在
  // forbidClick: true // 禁止点击
  showLoadingToast({
    message: '支付中...',
    forbidClick: true,
    duration: 0
  })
  // 调用支付接口
  const { data } = await payConsultOrder({
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    // payCallback表示支付成功后的跳转地址 'http://localhost:5173/room'
    payCallback: 'http://localhost:5173/room'
  })
  window.location.href = data.payUrl
}
</script>

<template>
  <div class="consult-pay-page" v-if="patientDetail && payInfo">
    <cp-nav-bar title="支付" :right-text="''" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.actualPayment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息" :value="briefPatientInfo"></van-cell>
      <van-cell
        title="病情描述"
        :label="consultStore.consult.illnessDesc"
      ></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      :loading="loading"
      @submit="onSubmit"
    />
  </div>
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" :right-text="''" />
    <van-skeleton title avatar :row="10" style="margin-top: 10px" />
  </div>

  <van-action-sheet
    v-model:show="show"
    title="选择支付方式"
    :closeable="false"
    :close-on-popstate="false"
    :before-close="handleClose"
  >
    <div class="pay-type">
      <p class="amount">￥{{ payInfo?.actualPayment.toFixed(2) }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === 0"
          /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === 1"
          /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay"
          >立即支付</van-button
        >
      </div>
    </div>
  </van-action-sheet>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
